<template>
  <!-- 交通事件的添加 修改 -->
  <div>
    <el-sub-menu index="3-1">
      <template #title>事件添加</template>
      <el-menu-item index="3-1-1" @click="addCustomEvent">
        添加自定义事件
      </el-menu-item>
      <el-menu-item index="3-1-2">
        <!-- 添加审核通过事件 -->
        <add-auditpassevent></add-auditpassevent>
      </el-menu-item>
    </el-sub-menu>
    <el-menu-item index="3-2" @click="updateClickEvent">事件更新</el-menu-item>
  </div>
  <!-- 创建弹框 -->
  <el-dialog
    v-model="eventTraDialogVis"
    width="400"
    :title="traEventTitle"
    draggable
    :modal="false"
    append-to-body
    :destroy-on-close="true"
  >
    <el-form
      label-width="100px"
      :model="eventFormTra"
      style="max-width: 460px"
      ref="ruleFormRefTra"
      :rules="rulesTra"
    >
      <el-form-item label="事件编号" prop="eventNum">
        <el-input v-model="eventFormTra.eventNum" />
      </el-form-item>
      <el-form-item label="事件类型" prop="eventType">
        <el-select
          v-model="eventFormTra.eventType"
          placeholder="碰撞"
          clearable
        >
          <el-option label="碰撞" value="碰撞" />
          <el-option label="失火" value="失火" />
          <el-option label="碾压" value="碾压" />
          <el-option label="刮擦" value="刮擦" />
          <el-option label="翻车" value="翻车" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="事件等级" prop="eventLevel">
        <el-select
          v-model="eventFormTra.eventLevel"
          placeholder="轻微事故"
          clearable
        >
          <el-option label="轻微事故" :value="1" />
          <el-option label="一般事故" :value="2" />
          <el-option label="重大事故" :value="3" />
          <el-option label="特大事故" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="发生时间" prop="date">
        <el-date-picker
          v-model="eventFormTra.date"
          type="date"
          placeholder="Pick a date"
          clearable
        />
      </el-form-item>
      <el-form-item label="发生地点" prop="address">
        <el-input v-model="eventFormTra.address" />
      </el-form-item>
      <el-form-item label="车牌号">
        <el-input v-model="eventFormTra.carId" />
      </el-form-item>
      <el-form-item label="驾驶员">
        <el-input v-model="eventFormTra.driver" />
      </el-form-item>
      <el-form-item label="处理状态" prop="status">
        <el-select v-model="eventFormTra.status" placeholder="待处理" clearable>
          <el-option label="待处理" :value="0" />
          <el-option label="处理中" :value="1" />
          <el-option label="已归档" :value="2" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitEventForm(ruleFormRefTra)">
          提交
        </el-button>
        <el-button @click="resetEventForm(ruleFormRefTra)">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
/* 添加更新 都需获取 事件图层 共用一个弹框
添加 不需要高亮图层 用户直接使用画笔 画点
     获取弹框表单数据 设置点的属性信息几何信息 添加到地图文档
更新 点击展示高亮图层 设置点不同颜色 点击点弹框 修改表单数据
     获取弹框表单数据 设置点的属性信息几何信息 添加到地图文档（）
*/
import { app } from "../../../../../main";
import { Query } from "../../../../../utils/Query";
import { Point } from "../../../../../utils/Point";
import { createDraw } from "../../../../../utils/createDraw";
import { formattedDate } from "../../../../../utils/formatTime";
import { TraEventManageHooks } from "./TraEventManageHooks";
import AddAuditpassevent from "./AddAuditpassevent.vue";
let $map = null;
let $docLayer = null;
// let popup = null;
onMounted(() => {
  $map = inject("$map");
  $docLayer = inject("$docLayer");
});
const { addEventPoint, trafficEventStyle, updateEventPoint } =
  TraEventManageHooks();

/* 交通事件弹框 */
const eventTraDialogVis = ref(false);
const traEventTitle = ref("");
// 表单dom 表单数据
const ruleFormRefTra = ref();
const eventFormTra = reactive({
  eventNum: "",
  eventType: "",
  eventLevel: "",
  date: "",
  address: "",
  carId: "",
  driver: "",
  status: "",
});
// 表单校验规则
const rulesTra = reactive({
  eventNum: [
    { required: true, message: "请提供事件编号", trigger: "blur" },
    { min: 2, max: 50, trigger: "blur" },
  ],
  eventType: [{ required: true, message: "请选择事件类型", trigger: "blur" }],
  eventLevel: [{ required: true, message: "请选择事件等级", trigger: "blur" }],
  address: [
    { required: true, message: "请输入发生地点", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  date: [{ required: true, message: "请输入发生时间", trigger: "blur" }],
  status: [{ required: true, message: "请选择处理状态", trigger: "blur" }],
});
// 自动填充表单 传入表单数据和事件点的属性对象
const formAutofill = (formData, attr) => {
  eventFormTra.eventNum = attr.事件编号;
  eventFormTra.eventType = attr.事件类型;
  eventFormTra.eventLevel = Number(attr.事件等级);
  eventFormTra.date = attr.发生时间;
  eventFormTra.address = attr.发生地点;
  eventFormTra.carId = attr.车牌号;
  eventFormTra.driver = attr.驾驶员;
  eventFormTra.status = Number(attr.处理状态);
};
// 清空重置表单
const formReset = (formData) => {
  eventFormTra.eventNum = "";
  eventFormTra.eventType = "";
  eventFormTra.eventLevel = "";
  eventFormTra.date = "";
  eventFormTra.address = "";
  eventFormTra.carId = "";
  eventFormTra.driver = "";
  eventFormTra.status = "";
};

/* ===事件添加=== */
// 添加自定义事件
// 画笔画点 弹框 表单 属性 几何 添加
// 获取要添加的点
let featureaCustomEvent = null;
const addCustomEvent = () => {
  // 重置表单，防止事件更新的自动填充表单影响事件添加
  formReset();
  // 自动填充事件添加的事件编号和发生时间
  eventFormTra.date = formattedDate();
  let str = "SJ" + formattedDate();
  eventFormTra.eventNum = str.replace(/[\s/:]/g, "");
  // 设置弹框标题
  traEventTitle.value = "添加自定义事件";
  // 创建交通画笔
  let drawSourceTraf = new ol.source.Vector({});
  let drawLayerTraf = new ol.layer.Vector({
    source: drawSourceTraf,
  });
  let drawTraf = createDraw({
    source: drawSourceTraf,
    type: "Point",
  });
  $map.addLayer(drawLayerTraf);
  $map.addInteraction(drawTraf);
  // 画笔按下事件 添加点
  drawTraf.on("drawend", (evt) => {
    // 获取要添加的点
    featureaCustomEvent = evt.feature;
    // 显示弹框
    eventTraDialogVis.value = true;
    // 移除画笔
    $map.removeLayer(drawLayerTraf);
    $map.removeInteraction(drawTraf);
  });
};

/* ===事件更新=== */
// 点击事件更新 切换高亮图层显隐
// 点击事件 出现弹框 获取点击的要素 根据要素属性填充表单
// 修改表单处理状态 提交表单

// 获取要修改的点
let featureUpdateEvent = null;
// 设置不同颜色的高亮图层
let sourceHighTEvtUpdate = new ol.source.Vector({});
let layerHighTEvtUpdate = new ol.layer.Vector({
  source: sourceHighTEvtUpdate,
});
// 获取所有的事件点，同步设置不同处理状态的点颜色
const successTEvtUpdate = (data) => {
  let format = new Zondy.Format.PolygonJSON();
  let features = format.read(data);
  // console.log(features, 222);
  features.forEach((item) => {
    let styleTrafEvt = trafficEventStyle(item.values_.values_.处理状态);
    item.setStyle(styleTrafEvt);
    // console.log( item.values_.values_.处理状态);
  });
  sourceHighTEvtUpdate.addFeatures(features);
};

// 更新事件后需要重新渲染事件点，修改更新的点的颜色
const resetTraEvtPointStyle = () => {
  // 清空之前的数据源
  sourceHighTEvtUpdate.clear();
  // 再执行查询，重新设置数据源,设置点颜色
  Query.queryByLayer({
    service: { name: "guanggu", layerId: 2 },
    success: successTEvtUpdate,
  });
};

// 地图点击回调函数 获取更新点 渲染弹框
const getUpdateTraEvtPoint = (evt) => {
  // console.log(evt, 77);
  // 要更新的事件点
  featureUpdateEvent = $map.forEachFeatureAtPixel(
    evt.pixel,
    (feature, layer) => {
      return feature;
    }
  );
  // console.log(featureUpdateEvent, 888);
  // 渲染弹框
  if (featureUpdateEvent) {
    // 事件点属性
    let attr = featureUpdateEvent.getProperties().getProperties();
    // let FID = featureUpdateEvent.getId();
    // let position = featureUpdateEvent.getGeometry().getFlatCoordinates();
    // console.log(attr, 999);
    // console.log(FID, 999);
    // console.log(position, 999);
    // 自动填充表单
    formAutofill(eventFormTra, attr);
    // 设置弹框标题
    traEventTitle.value = "事件更新";
    // 显示弹框
    eventTraDialogVis.value = true;
  }
};

// 设置事件更新点图层的显隐
let isShowTraEvtUpdate = false;
const updateClickEvent = () => {
  isShowTraEvtUpdate = !isShowTraEvtUpdate;
  if (isShowTraEvtUpdate) {
    // 每次点击都要重新获取数据源，防止事件添加的点无法加入高亮图层
    // 清空之前的数据源
    sourceHighTEvtUpdate.clear();
    Query.queryByLayer({
      service: { name: "guanggu", layerId: 2 },
      success: successTEvtUpdate,
    });
    // 添加事件点不同样式的高亮图层
    $map.addLayer(layerHighTEvtUpdate);
    // 获取要更新的事件点 弹出渲染弹框
    $map.on("click", getUpdateTraEvtPoint);
  } else {
    $map.removeLayer(layerHighTEvtUpdate);
    $map.un("click", getUpdateTraEvtPoint);
  }
};

// 表单提交
const submitEventForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // 表单验证 valid 有效
      // console.log("提交成功!");
      // 表单数据
      // console.log(eventFormTra, 77);
      // 将点添加到地图文档
      if (traEventTitle.value === "添加自定义事件") {
        // console.log(featureaCustomEvent, 77);
        addEventPoint(eventFormTra, featureaCustomEvent, $docLayer);
      } else if (traEventTitle.value === "事件更新") {
        // 获取要更新的事件点 表单数据 进行更新
        updateEventPoint(eventFormTra, featureUpdateEvent, $docLayer);
        // 重新渲染高亮图层
        resetTraEvtPointStyle();
      }
      // 隐藏弹框
      eventTraDialogVis.value = false;
    } else {
      // 表单验证 valid 无效
      // console.log("提交失败!");
      return false;
    }
  });
};
// 表单重置
const resetEventForm = (formEl) => {
  if (!formEl) return;
  formReset();
  // 隐藏弹框
  eventTraDialogVis.value = false;
};
</script>

<style lang="scss" scoped>
#tem-popup {
  background-color: #fff;
  .pop_header {
    background-color: #2196f3;
  }
}
</style>
